import { Component } from 'react';
import {Group, Boxs, Tab, SearchBar, TextareaField, ScrollList, Button, Toast, Dialog, Badge} from 'saltui';
const { HBox,VBox, Box } = Boxs;
const { IconButton } = Button;
import MyTabBar from 'components/tab_bar';
import { URLS,nodataIcon } from '../../../app/variables';
import DB from '../../../app/db';
import Radio from 'components/radio';
import './PageHome.less';
const currentItem = { activeItem: "1", flag: false,isloading: false};

const ReceivedItem  =  React.createClass({
  detailsClick: function(event) {
    if(!currentItem.isloading){
      let t = this;
      DB.SomeModuleAPI.entityIsExist({id:t.props.applyRecordid}).then((content) => {
        if(content == 'exist'){
          currentItem.flag = true;
          let url ='meeting/myMeetingDetails/'+t.props.applyRecordid + '/myReceived';
          location.hash=url;
        }else{
          Toast.show({
              type: 'error',
              content: '当前数据已删除',
          });
          t.props.refreshList();
        }
      }).catch((error) => {
      });
    }
  },
  invitationClick:function(){
    location.hash = 'meeting/turnover/' + this.props.noticeInfoId + '/' + this.props.applyRecordid;
  },
  dontAttendClick:function(){
    this.props.dontAttendClick(this.props.noticeInfoId);
  },
  attendClick:function(){
    this.props.attendClick(this.props.meetingWay, this.props.noticeInfoId);
  },
  render:function() {
       return <div className="t-BCf t-MT10 t-R4 t-MR8 t-ML8">
        <Box className="t-P12 dd-bottom-border" style={{borderTop:'5px solid #38acff'}} onClick={this.detailsClick}>
          <HBox>
            <Box>
              <Badge className={this.props.is_cycle==1 && this.props.cycle_type==0?'':'t-DN'} text={'日例会'} style={{marginRight: 7,background: '#38adff',height:18,lineHeight:'18px',borderRadius:'10px',padding:'0 8px'}}/>
              <Badge className={this.props.is_cycle==1 && this.props.cycle_type==1?'':'t-DN'} text={'周例会'} style={{marginRight: 7,background: '#38adff',height:18,lineHeight:'18px',borderRadius:'10px',padding:'0 8px'}}/>
              <Badge className={this.props.is_cycle==1 && this.props.cycle_type==2?'':'t-DN'} text={'月例会'} style={{marginRight: 7,background: '#38adff',height:18,lineHeight:'18px',borderRadius:'10px',padding:'0 8px'}}/> 
            </Box>
            <Box flex={1}>
              <p className="t-FS16">{this.props.applyRecordName}</p>
            </Box>
          </HBox>
          <p className="t-MT6">
            <span className="t-MR10 t-FCddfontblue-60 ">
            <i className="iconfont icon-time t-FCddfontblue-60 t-MR4 t-FS12"></i>
              {this.props.startTime ? this.props.startTime.substring(5,16) : ''}
            </span>
            <span className="t-FCddfontblue-60">
              <i className="iconfont icon-place t-FCddfontblue-60 t-MR4 t-FS12"></i>
              {this.props.boardroomId ? this.props.boardroomName : this.props.address ? this.props.address :"无"}
            </span>
          </p>
        </Box>
        <Box>
          <span className={this.props.status==2 && this.props.attendWay != 2 ? "t-FL t-P12 t-FCddfontblue-60":"t-DN"}>{'已确认参会-' + (this.props.attendWay == 1 ? "现场参会" : this.props.attendWay == 2 ? "网络参会" : "" )}</span>
  <span className={this.props.status==3 ? "t-FL t-P12 t-FCddfontblue-60":"t-DN"}>不参会:{this.props.reason}</span>
          <span className={this.props.status==9 ? "t-FL t-P12 t-FCddfontblue-60":"t-DN"}>{this.props.inviter + '邀请您参加会议'}</span>
          <span className={this.props.status==2 && this.props.attendWay == 2 ? "t-FL t-P12 t-FCddfontblue-60":"t-DN"} onClick={this.joinQS}>点击进入网络会议</span>
          <div className="t-FR t-MT8">
            <Button className={this.props.status!=9 && this.props.inviter == null ? "t-R20 t-MR8":"t-DN"} type="secondary" size="small" display="inline" onClick={this.invitationClick}>邀请</Button>
            <Button className={this.props.status!=3 ? "t-R20 t-MR8":"t-DN"} type="secondary" size="small" display="inline" onClick={this.dontAttendClick}>不参会</Button>
            <Button className={this.props.status!=2 ? "t-R20 t-MR8":"t-DN"} type="primary" size="small" display="inline" onClick={this.attendClick}>参会</Button>
          </div>
        </Box>
      </div>
    },

    joinQS:function () {
      //alert("入会");
      var thirdMenuType = getLoginUserInfo().thirdMenuType;
      //alert("thirdMenuType:"+thirdMenuType);

      if(thirdMenuType=="MH"){
        var curuserid = this.props.user_id;
        var emceeuser = this.props.emceeUserId;
        var creater = this.props.createdBy;

        var qsuserId = this.props.qsuserId;
        var qsusername = this.props.qsusername;
        var qsmeetingId = this.props.qsmeetingId;
        var meetingCode = this.props.attUserPass;
        var emceeUserPass = this.props.emceeUserPass;
        //主持人参会
        if(curuserid==creater){
          meetingCode = emceeUserPass;
        }
        //alert("qsuserId:"+qsuserId+" qsusername:"+qsusername+" qsmeetingId:"+qsmeetingId+" meetingCode:"+meetingCode);

         //全时入会
         !!emp&&emp.quanshi.openQuanshiMeeting({
           userId: qsuserId,//用户的全时账号 "7300567@zoomlion.com"
           username: qsusername,//用户名字 "张三"
           meetingId: qsmeetingId,//会议id '21312423'
           meetingCode: meetingCode  //会议密码 "xxxxxx"
         });
      }
    }
 });

const SendItem  =  React.createClass({
  detailsClick: function(event) {
    if(!currentItem.isloading){
        let t = this;
        DB.SomeModuleAPI.entityIsExist({id:t.props.id}).then((content) => {
          if(content == 'exist'){
            currentItem.flag = true;
            let url ='meeting/myMeetingDetails/'+t.props.id + '/mySend';
            location.hash=url;
          }else{
            Toast.show({
                type: 'error',
                content: '当前数据已删除',
            });
            t.props.refreshList();
          }
        }).catch((error) => {
        });
    }
  },
  
  render:function() {
    let startTime = this.props.startTime ? this.props.startTime.substring(5,16) : '';
    let endTime = this.props.endTime ? this.props.endTime.substring(5,16) : '';
       return <div>         
        <HBox className="t-BCf t-P16 t-PR0 dd-bottom-border" onClick={this.detailsClick}>
          <Box flex={1}>
            <div className="t-omit t-FC3 t-FS16 t-LH1_3 t-MR8">
              {this.props.meetingName}
            </div>
            <HBox className="t-FCddfontblue-40 t-LH1_3 t-PT8 t-FS14" vAlign="center">
              <i className="iconfont icon-time t-MR4 t-FS14"></i>
              <span className="t-omit">{startTime}~{endTime}</span>
            </HBox>
            <HBox className="t-FCddfontblue-40 t-LH1_3 t-PT6 t-FS14" vAlign="center">
              <i className="iconfont icon-place t-MR4 t-FS14"></i>
              <span className="t-omit">{this.props.boardroomId ? this.props.boardroomName : this.props.address ? this.props.address :"无"}</span>
            </HBox>
          </Box>
          <VBox vAlign="center" className="z-AIFE t-MR16">
            <Box  className={this.props.status==5?'z-WFC t-H22 t-LH22 t-DIB light-badge badge-lightgrey':'t-DN'}>已结束</Box>
            <Box  className={this.props.status==4?'z-WFC t-H22 t-LH22 t-DIB light-badge badge-lightgreen':'t-DN'}>进行中</Box>
            <Box  className={this.props.status==3?'z-WFC t-H22 t-LH22 t-DIB light-badge badge-lightred':'t-DN'}>已取消</Box>
            <Box  className={this.props.status==1?'z-WFC t-H22 t-LH22 t-DIB light-badge badge-lightred':'t-DN'}>未召开</Box>
          </VBox>
        </HBox>           
      </div>
    }
 });

export default class PageHome extends Component {

 constructor(props) {
    super(props);

   Dialog.hide();
   //修改待办列表页tab默认值
   document.getElementById("sendTabIndex").value = "0";
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
    //是否需要底部tab页
    var hasBottomTab =  document.getElementById("hasBottomTab").value;
    var winHeight = getScrollHigh(1, 1, hasBottomTab);

    var activeItem = '1';
    if(currentItem.flag){
      activeItem = currentItem.activeItem;
    }
    currentItem.flag = false;
    let attendWays = [
      { text:"现场参会", value:1 },
      { text:"网络参会", value:2 }
    ];
    this.state = {
      search0:'',
      search1:'',
      noDataTip0:'暂无数据',
      noDataTip1:'暂无数据',
      activeItem: activeItem,
      winHeight:winHeight,
      hasBottomTab: hasBottomTab,
      attendWays:attendWays,
      attendWay:attendWays[0],
      reason:'',
      showDontAttendDialog:false,
      showAttendDialog:false,
      currentNoticeInfoId:'',
      currentMeetingWay:0,
    };

  }

  componentDidMount(){
    var page_title = "会议";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
        title : page_title,//控制标题文本，空字符串表示显示默认文本
        onSuccess : function(result) {},
        onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
        title: {
            text: page_title,
            icon: '',
            actionmenu: {}
        },
      });
    }
    searchBarLimit(20);
  }

  // 请求参数
  beforeFetch0(data,from){
    currentItem.isloading = true;
    if (from.title == undefined) {
      data.condition = this.state.search0;
    } else {
      data.condition = from.title;
    }
    return data;
  }

  beforeFetch1(data,from){
    currentItem.isloading = true;
    if (from.title == undefined) {
      data.condition = this.state.search1;
    } else {
      data.condition = from.title;
    }
    return data;
  }

  returnData(data){ 
    currentItem.isloading = false;
    return data;
  }

  fetchData1(param){
    this.refs.meeting_received_ref.fetchData({title:''});
  }

  fetchData0(param){
    this.refs.meeting_send_ref.fetchData({title:''});
  }

  //搜索
  onSearch(type,keyword) {
    if (type == 0) {
      this.setState({
        search0:keyword,
        noDataTip0:'无搜索结果'
      });
      this.refs.meeting_send_ref.fetchData({title:keyword});
    } else if (type == 1) {
      this.setState({
        search1:keyword,
        noDataTip1:'无搜索结果'
      });
      this.refs.meeting_received_ref.fetchData({title:keyword});
    }
  }

  //退出
  onExit(type,keyword){
    if (type == 0) {
      this.setState({
        search0:'',
        noDataTip0:'暂无数据'
      });
      this.refs.meeting_send_ref.fetchData({title:''});
    } else if (type == 1) {
      this.setState({
        search1:'',
        noDataTip1:'暂无数据'
      });
      this.refs.meeting_received_ref.fetchData({title:''});
    }
  }

  handleChange(obj) {
    this.setState({
      activeItem: obj.active,
      search0: '',
      search1:'',
    });
    currentItem.activeItem = obj.active;
    searchBarLimit(20);
  }

  applyMeeting(){
    location.hash = 'meeting/addNotice';
  }

  //不参会
  dontAttendClick(noticeInfoId){
    this.setState({
      showDontAttendDialog: true,
      currentNoticeInfoId: noticeInfoId
    });
  }

  dontAttend(){
    let t = this;
    if (t.state.reason.trim() == '') {
      t.setState({
        showDontAttendDialog: false,
      },function(){
        setTimeout(function(){
          t.setState({
            showDontAttendDialog: true,
          })
        },1500);
        Toast.show({
          type: 'error',
          content: '请输入不参会原因',
        });
      })
      return false;
    }
    let param = {
      id: t.state.currentNoticeInfoId,
      status: 3,
      reason: t.state.reason,
    };
    DB.SomeModuleAPI.editNoticeInfoStatus(param).then((content) => {
      if(content.code == -1){
        Toast.show({
          type: 'error',
          content: content.message,
        });
      }
      t.fetchData1();
      t.setState({
        showDontAttendDialog: false,
        reason:'',
      });
    }).catch((error) => {
    });
  }

  //点击参会
  attendClick(meetingWay, noticeInfoId){
    let t = this;
    if(meetingWay == 2){
      t.setState({
        showAttendDialog: true,
        currentNoticeInfoId: noticeInfoId
      });
    }else{
      Dialog.confirm({
        title: '提示',
        content: '确定参加会议？',
        onConfirm() {
          t.attendMeeting(noticeInfoId, meetingWay == 0 ? 1 : 2);
          t.fetchData1();
          t.setState({
            showAttendDialog: false,
          });
        },
      });
      
    }
  }

  //参会
  attendMeeting(noticeInfoId, attendWay){
    let t = this;
    let param = {
      id: noticeInfoId ? noticeInfoId : t.state.currentNoticeInfoId,
      status: 2,
      attendWay: attendWay ? attendWay : t.state.attendWay.value,
    };
    DB.SomeModuleAPI.editNoticeInfoStatus(param).then((content) => {
      if(content.code == -1){
        Toast.show({
          type: 'error',
          content: content.message,
        });
      }
      t.fetchData1();
      this.setState({
        showAttendDialog: false,
      });
    }).catch((error) => {
    });
  }
  
  dialogChange(field, value){
    this.setState({
      [field]: value
    })
  }

  handleTextChange(field, newValue, size) {
    if (newValue.length <= size) {
      this.setState({
        [field]: newValue,
      });
    }
  }
  
  dialogCancle(){
    this.setState({
      showDontAttendDialog: false,
      showAttendDialog: false
    });
  }

  render() {
    const t = this;
    let listHeight = {height: this.state.winHeight};
    return (
      <div className="page-meeting">
        <div className="my-meeting">
          <Tab activeKey={this.state.activeItem} onChange={this.handleChange.bind(this)}>
            <Tab.Item title="我收到的" key="1">
              <SearchBar hasHistory={false} instantSearch={false} onSearch={this.onSearch.bind(this,1)}  ref='received_search' placeholder='请输入会议名称' onExit={this.onExit.bind(this,1)}>
              </SearchBar>
              <div style={listHeight}>
                <ScrollList
                  url={URLS.receivedNoticeList}
                  dataType="json"
                  pageSize={10}
                  beforeFetch={this.beforeFetch1.bind(this)}
                  noDataTip={this.state.noDataTip1}
                  processData={this.returnData.bind(this)} 
                  ref = 'meeting_received_ref'
                  noDataImage={nodataIcon}
                  scrollLoad={true}
                  currentPageKey="page">
                  <ReceivedItem 
                    refreshList={this.fetchData1.bind(this)} 
                    dontAttendClick={(noticeInfoId)=>{t.dontAttendClick(noticeInfoId)}}
                    attendClick={(meetingWay, noticeInfoId)=>{t.attendClick(meetingWay, noticeInfoId)}}/>
                </ScrollList>
              </div>
            </Tab.Item>
            <Tab.Item title="我发出的" key="0">
              <SearchBar hasHistory={false} instantSearch={false} onSearch={this.onSearch.bind(this,0)}  ref='myCycleeeting_search' placeholder='请输入会议名称' onExit={this.onExit.bind(this,0)}>
              </SearchBar>
              <div style={listHeight}>
                <ScrollList
                  url={URLS.sendNoticeList}
                  dataType="json"
                  pageSize={10}
                  beforeFetch={this.beforeFetch0.bind(this)}
                  noDataTip={this.state.noDataTip0}
                  processData={this.returnData.bind(this)} 
                  ref = 'meeting_send_ref'
                  noDataImage={nodataIcon}
                  scrollLoad={true}
                  currentPageKey="page">
                  <SendItem refreshList={this.fetchData0.bind(this)}/>
                </ScrollList>
              </div>
            </Tab.Item >
          </Tab>
        </div>
        <MyTabBar activeIndex={0} />
        <IconButton className="add-new-page t-BCddblue" onClick={this.applyMeeting.bind(this)}><i className="iconfont icon-plus t-FCf"></i></IconButton>
      
        <Dialog
          key="dontAttend-confirm"
          title="提示"
          show={this.state.showDontAttendDialog}
          type="confirm"
          onConfirm={() => { t.dontAttend(); }}
          onCancel={() => { t.dialogCancle(); }}
        >
          <Group.List >
            <TextareaField
                layout="v"
                placeholder="请输入不参会原因"
                value={this.state.reason}
                onChange={(value) => { t.handleTextChange('reason', value, 20); }}
            />
          </Group.List>
        </Dialog>

        <Dialog
          key="attend-confirm"
          title="请选择参会方式"
          show={this.state.showAttendDialog}
          type="confirm"
          onConfirm={() => { t.attendMeeting(); }}
          onCancel={() => { t.dialogCancle(); }}
        >
          <Radio
            data={t.state.attendWays}
            value={t.state.attendWay}
            onChange={(value)=>{ t.dialogChange('attendWay', value);}}
          ></Radio>
        </Dialog>
      </div>
    );
  }
}


